$(document).ready(function() {
    $("#myForm").validate({
        rules: {
            username: {
                required: true,
                minlength: 2
            },
            password: {
                required: true,
                minlength: 6
            },
            email: {
                required: true,
                email: true
            }
        },
        messages: {
            username: {
                required: "请输入用户名",
                minlength: "用户名至少为2个字符"
            },
            password: {
                required: "请输入密码",
                minlength: "密码至少为6个字符"
            },
            email: {
                required: "请输入邮箱",
                email: "请输入正确的邮箱地址"
            }
        }
    });
});

$("#myForm").on("submit", function(event) {
    event.preventDefault();
    if ($("#myForm").valid()) {
        $.ajax({
            url: "http://localhost:8080/user/add",
            type: "POST",
            contentType: "application/json", // 设置内容类型为JSON
            data: JSON.stringify({
                username: $("#username").val(),
                password: $("#password").val(),
                email: $("#email").val()
            }), // 使用JSON格式发送数据
            success: function(response) {
                // 确保服务器返回response包含username和email字段。
                $("#result").html("用户名：" + response.username + "<br>邮箱：" + response.email);
            },
            error: function(xhr, status, error) {
                alert("提交失败，请重试");
                console.error(status, error.toString()); // 更详细地输出错误信息。
            }
        });
    }
});

function getUserInfo() {
    var username = $("#username").val();
    $.ajax({
        type: "GET",
        url: "http://localhost:8080/user/get/" + username,
        success: function (response) {
            if (response) {
                var email = response.email;
                $("#result").html("用户名：" + username + "<br>邮箱：" + email);
            } else {
                alert("未找到该用户");
            }
        }
    });
}